package com.ask.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ask.constant.MessageConstant;
import com.ask.context.BaseContext;
import com.ask.dto.*;
import com.ask.entity.*;
import com.ask.exception.AddressBookBusinessException;
import com.ask.exception.OrderBusinessException;
import com.ask.exception.ShoppingCartBusinessException;
import com.ask.mapper.*;
import com.ask.result.PageResult;
import com.ask.service.OrderService;
import com.ask.vo.OrderPaymentVO;
import com.ask.vo.OrderStatisticsVO;
import com.ask.vo.OrderSubmitVO;
import com.ask.vo.OrderVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
//    @Autowired
//    private WebSocketServer webSocketServer;

    /**
     * 提交订单
     *
     * @param orderDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrderDTO orderDTO) {
        // 业务异常校验 - 地址簿
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = addressBookMapper.getById(orderDTO.getAddressBookId());
        if (addressBook == null)
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);

        // 获取当前用户的购物车
        ShoppingCart cart = ShoppingCart.builder().userId(userId).build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(cart);
        if (shoppingCartList == null || shoppingCartList.isEmpty())
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        // 设置订单的各种属性
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderDTO, orders);

        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);

        // 新增orders表
        orderMapper.myInsert(orders);

        // 新增order_detail表
        List<OrderDetail> orderDetails = new ArrayList<>();
        shoppingCartList.forEach(item -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });

        orderDetailMapper.insertBatch(orderDetails);

        // 删除用户的购物车数据
        shoppingCartMapper.deleteByUserID(userId);

        // 封装VO返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        if (orderDetailList != null && !orderDetailList.isEmpty())
            orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 查询历史订单
     *
     * @param pageSize
     * @return
     */
    @Override
    public PageResult pageQuery4User(Integer page, Integer pageSize, Integer status) {
        // 分页查询Orders
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = OrdersPageQueryDTO.builder()
                .page(page)
                .pageSize(pageSize)
                .status(status)
                .userId(BaseContext.getCurrentId()).
                build();

        // 分页查询结果，其实是一个List<Orders>  Page<E> extends ArrayList<E>
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);

        // 查询orderDetail表, 封装orderVOList
        List<OrderVO> orderVOList = new ArrayList<>();

        ordersPage.forEach(order -> {
            // 根据orderId查询orderDetail
            List<OrderDetail> details = orderDetailMapper.getByOrderId(order.getId());
            // 封装VO对象
            OrderVO orderVO = new OrderVO();

            BeanUtils.copyProperties(order, orderVO);
            orderVO.setOrderDetailList(details);
            orderVOList.add(orderVO);
        });
        return new PageResult(ordersPage.getTotal(), orderVOList);
    }

    /**
     * 取消订单
     *
     * @param orderId
     */
    @Override
    public void cancelOrder(Long orderId) {
        // 订单是否存在？
        Orders order = orderMapper.getById(orderId);
        if (order == null)
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);

        // 订单的状态是否允许取消: status 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (order.getStatus() > 2)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        // 订单处于待接单状态？
        if (order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            // todo 调用微信的退款接口
        }

        // 跟新Order表
        Orders orderToUpdate = Orders.builder()
                .id(orderId)
                .status(Orders.CANCELLED)
                .cancelReason("取消订单")
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orderToUpdate);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 获取订单的详细信息
        List<OrderDetail> details = orderDetailMapper.getByOrderId(id);

        // 批量插入shoppingCart表
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail detail : details) {
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(detail, cart, "id");
            cart.setUserId(BaseContext.getCurrentId());
            cart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(cart);
        }
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(dto);
        List<OrderVO> orderVOList = getOrderVOList(page);
        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * getStatistics
     *
     * @return
     */
    @Override
    public OrderStatisticsVO getStatistics() {
        // select count(*) from orders where status = 1
        Integer confirmed = orderMapper.getCountByStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.getCountByStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer toBeConfirmed = orderMapper.getCountByStatus(Orders.TO_BE_CONFIRMED);

        return OrderStatisticsVO.builder()
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .toBeConfirmed(toBeConfirmed)
                .build();
    }

    /**
     * 接单
     *
     * @param id
     */
    @Override
    public void confirmOrder(Long id) {
        Orders orders = orderMapper.getById(id);
        if (!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException("订单状态异常！");
        }
        // 设置订单状态为已接单
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 取消订单（管理端）
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(@RequestBody OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        Integer payStatus = orders.getPayStatus();

        if (payStatus.equals(Orders.PAID)) {
            // todo 调用微信退款接口
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void deliveryOrder(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null || orders.getStatus() != Orders.CONFIRMED)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void completeOrder(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null || orders.getStatus() != Orders.DELIVERY_IN_PROGRESS)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param orderRejectDTO
     */
    @Override
    public void rejectOrder(OrderRejectDTO orderRejectDTO) {
        Orders orders = orderMapper.getById(orderRejectDTO.getId());
        if (orders == null || orders.getStatus() != Orders.TO_BE_CONFIRMED)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(orderRejectDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    // 获取订单的详细信息
    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        List<OrderVO> orderVOList = new ArrayList<>();
        List<Orders> ordersList = page.getResult();
        for (Orders orders : ordersList) {
            // 拷贝order的基本信息
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);

            // 获取订单的orderDishes信息
            String orderDishes = getOrderDishesStr(orders);
            orderVO.setOrderDishes(orderDishes);
            orderVOList.add(orderVO);
        }
        return orderVOList;
    }

    // 获取订单包含的菜品信息
    private String getOrderDishesStr(Orders orders) {
        // 查询订单的菜品详细信息
        List<OrderDetail> details = orderDetailMapper.getByOrderId(orders.getId());
        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3）
        List<String> orderDishList = details.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        Map map = new HashMap();
        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo);

        String json = JSON.toJSONString(map);
        //webSocketServer.sendToAllClient(json);
    }

    @Override
    public void reminder(Long id) {
        Orders orderDB = orderMapper.getById(id);
        if (orderDB == null)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号" + orderDB.getNumber());

        //kwebSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 批量插入
     * @param ordersList
     */
    @Override
    @Transactional
    public void insertBatch(List<Orders> ordersList) {
        orderMapper.insertBatch(ordersList);
    }

    public void deleteByUserId(Long userId) {
        orderMapper.deleteByUserId(userId);
    }
}
